package com.linsir.common.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.json.Json;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Ret;
import com.linsir.common.utils.xx;
import com.linsir.config.EovaConst;
import com.linsir.model.User;

import java.util.HashSet;

/**
 * @author Administrator
 * @title: BaseController
 * @projectName linsir-mu
 * @description: TODO
 * @date 2021/12/123:38
 */
public class BaseController extends Controller {
    public String http(String domain) {
        return "http://" + xx.getConfig(domain);
    }

    public int UID() {
        return getUser().getInt("id");
    }

    public int RID() {
        return getUser().getInt("rid");
    }

    public User getUser() {
        return (User) getSessionAttr(EovaConst.USER);
    }

    /**
     * <pre>
     * 获取选中行某列的值
     * 多选且为整型:1,2,3
     * 多选且为字符:'a','b','c'
     * PS:多选的处理方便取值后直接in
     * </pre>
     * @param field 字段名
     */
    public String getSelectValue(String field) {
        // 单选
        JSONArray rows = getSelectRows();
        if (rows.isEmpty()) {
            return null;
        }
        if (rows.size() == 1) {
            return rows.getJSONObject(0).getString(field);
        }

        boolean isNum = true;
        // 多选
        HashSet<String> set = new HashSet<>();
        for (int i = 0; i < rows.size(); i++) {
            Object val = rows.getJSONObject(i).get(field);
            set.add(val.toString());
            if (!xx.isNum(val))
                isNum = false;
        }
        if (isNum) {
            return xx.join(set);
        } else {
            return xx.join(set, "'", ",");
        }
    }

    public Integer getSelectValueToInt(String field) {
        return xx.toInt(getSelectValue(field));
    }

    /**
     * 获取所有选中行
     *
     * @return
     */
    public JSONArray getSelectRows() {
        String json = getPara("rows");
        JSONArray o = JSONObject.parseArray(json);
        return o;
    }

    /**
     * 获取按钮输入框的值
     * <pre>
     * Integer id = getSelectValue("id");
     *
     * if (xx.isEmpty(val)) {
     *     renderJson(new Easy("参数不能为空！"));
     *     return;
     * }
     *
     * Db.update("update xxx set xx = ? where id = ?", val, id);
     * renderJson(Easy.sucess());
     *</pre>
     */
    public String getInputValue() {
        return getPara("input");
    }

    /**
     * 获取JSONObject
     *
     */
    public Ret getJsonToRet() {
        String s = HttpKit.readData(getRequest());
        if (xx.isEmpty(s)) {
            return null;
        }
        return Json.getJson().parse(s, Ret.class);
        // return JSONObject.parseObject(HttpKit.readData(getRequest()));
    }

}
